package com.nancal.activiti.controller;

import com.alibaba.fastjson.JSONObject;
import com.nancal.activiti.controller.editor.ModelEditorJsonRestResource;
import com.nancal.activiti.controller.editor.ModelSaveRestResource;
import com.nancal.activiti.entity.Response;
import com.nancal.activiti.entity.ResponseCode;
import com.nancal.activiti.service.FileManageService;
import com.nancal.activiti.service.ModelImageService;
import com.nancal.activiti.service.ProcessDesignService;
import com.nancal.activiti.service.process.ProcessRuntimeService;
import com.nancal.activiti.utils.CloseableUtils;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


@RestController
@RequestMapping("/workflow")
public class ProcessDesignController {

    @Autowired
    private ProcessDesignService processDesignService;
    @Autowired
    private ModelSaveRestResource modelSaveRestResource;
    @Autowired
    private ModelEditorJsonRestResource modelEditorJsonRestResource;
    @Autowired
    ProcessRuntimeService processRuntimeService;
    @Autowired
    private ModelImageService modelImageService;
    @Autowired
    FileManageService fileManageService;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 创建模型
     */
    @RequestMapping(value = "/model/insert", method = RequestMethod.POST)
    public Response createModel(@RequestParam String key, @RequestParam String name, @RequestParam String module, @RequestParam String descp) throws UnsupportedEncodingException {
        Model model = repositoryService.createModelQuery().modelName(name).singleResult();
        if (model != null) {
            return Response.failure("该名称已存在，请重新输入");
        }
        String modelId = processDesignService.createModel(key, name, module, descp);
        return Response.success(modelId);
    }

//    @RequestMapping(value = "/model/insert", method = RequestMethod.POST)
//    public Response createModel(@RequestParam String key, @RequestParam String name, @RequestParam String module, @RequestParam String descp,@RequestParam("file") MultipartFile file) throws UnsupportedEncodingException {
//        String modelId = processDesignService.createModel(key, name, module, descp);
//        if (Objects.isNull(file)) {
//            return Response.failure("文件上传失败，请重新选择文件");
//        }
//        String upload = fileManageService.upload(file);
//        //往modelsvg表中添加表单信息
//        //modelImageService.addFileAndModelId(modelId,file.getOriginalFilename());
//        return Response.success(modelId);
//    }

    /**
     * 保存模型
     * http://locslhost:8080/workflow/model/{modelId}/xml/save
     */
    @RequestMapping(value = "/model/{modelId}/xml/save", method = RequestMethod.POST, produces = "application/json")
    public Response saveModelXml(@PathVariable String modelId, @RequestBody Map<String, String> values) {
        modelSaveRestResource.saveModelXml(modelId, values);
        byte[] svg_xmls = values.get("svg_xml").getBytes();

        //关联表单信息
        //String tableForm = values.get("tableForm");
        // 数据库中的字段为longblob
        modelImageService.addSvgBytesAndModelId(modelId, svg_xmls);
        return Response.success(ResponseCode.SUCCESS);

    }

    /**
     * 文件上传
     * http://localhost:8080/workflow/upload
     *
     * @param file
     * @return
     */
//    @RequestMapping("upload")
//    public Response fileUpload(MultipartFile file) {
//        if (Objects.isNull(file)) {
//            return Response.failure("文件上传失败，请重新选择文件");
//        }
//        String upload = fileManageService.upload(file);
//
//        return Response.success(upload);
//    }
    @RequestMapping("upload")
    public Response fileUpload(MultipartFile file, String modelId) {
        System.out.println(modelId);
        if (Objects.isNull(file)) {
            return Response.failure("文件上传失败，请重新选择文件");
        }
        String upload = fileManageService.upload(file, modelId);
        return Response.success(upload);
    }

    /**
     * 文件下载
     * http://localhost:8080/workflow/download?deploymentId=
     *
     * @param deploymentId
     * @param response
     * @return
     */
    @GetMapping("/download")
    public String fileDownload(@RequestParam("deploymentId") String deploymentId, HttpServletResponse response) {
        return fileManageService.download(deploymentId, response);
    }


    /**
     * 查询模板图片
     * http://localhost:8080/workflow/queryModelImg2?deploymentId=
     */
    @RequestMapping("/queryModelImg2")
    public void queryModelImg2(String deploymentId, HttpServletResponse response) {
        String svgByModelId = modelImageService.findSvgByModelId(deploymentId);
        ByteArrayInputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new ByteArrayInputStream(svgByModelId.getBytes());
            // 输出流程图
            outputStream = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = inputStream.read(b, 0, b.length)) != -1) {
                outputStream.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseableUtils.close(outputStream, inputStream);
        }

    }

    /**
     * 查看保存的模型图列表信息
     * http://localhost:8080/workflow/model/list
     *
     * @return
     */
    @RequestMapping(value = "/model/list", method = RequestMethod.GET)
    public Response listModel() {
        List<Map<String, Object>> listModel = processDesignService.listModel();
        return Response.success(listModel);
    }


    /**
     * 查询模板图片
     * http://localhost:8080/workflow/queryModelImg?deploymentId=95001
     */
    @RequestMapping("/queryModelImg")
    public void queryModelImg(String deploymentId, HttpServletResponse response) {
        processDesignService.queryModelImg(deploymentId, response);
    }

    /**
     * 部署流程
     * http://localhost:8080/workflow/model/deploy?modelId=92505
     *
     * @param modelId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/model/deploy")
    public Response deploy(@RequestParam(name = "modelId") String modelId) throws Exception {
        String result = processDesignService.deployModel(modelId);
        if (result.equals("success")) {
            return Response.success(result);
        } else {
            return Response.failure(result);
        }
    }

    /**
     * 部署流程(用于部署本地的流程)
     * http://localhost:8080/workflow/model/localDeploy?processName=processName&modelName=modelName
     *
     * @param processName
     * @param modelName
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/model/localDeploy")
    public Response localDeploy(String processName, String modelName) {
        String result = processDesignService.localDeployModel(processName, modelName);
        if (result.equals("success")) {
            return Response.success(result);
        } else {
            return Response.failure(result);
        }
    }

    /**
     * 删除部署流程及模板
     * http://localhost:8080/workflow/deleteModel?modelId=95001
     *
     * @param modelId
     * @return
     */
    @GetMapping(value = "/deleteModel")
    public Response flowDelete(@RequestParam(name = "modelId") String modelId) {
        String result = processDesignService.deleteModel(modelId);
        if (result.equals("删除成功")) {
            return Response.success(result);
        } else {
            return Response.failure(result);
        }

    }

    /**
     * 根据生成的ID获取模型流程编辑器
     * 用于模板流程修改
     * http://localhost:8080/workflow/model/{modelId}/xml
     *
     * @param modelId
     * @return
     */
    @RequestMapping(value = "/model/{modelId}/xml", method = RequestMethod.GET, produces = "application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public Response getEditorXml(@PathVariable String modelId) {
        JSONObject jsonObject = modelEditorJsonRestResource.getEditorXml(modelId);
        return Response.success(jsonObject);
    }


    /**
     * 查询已发布的模型图（流程）
     * http://localhost:8080/workflow/findAllProcessInstance
     */
    @GetMapping("/findAllProcessInstance")
    public Response findAllProcessInstance() {
        List<Map<String, Object>> listModel = processDesignService.listModelDeploy();
        return Response.success(listModel);
    }


}
